package com.sumainfor.common.config;


import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.log4j.Log4j2;
import okhttp3.ConnectionPool;
import org.apache.commons.codec.binary.Base64;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * @Author PuaChen
 * @Create 2018-11-03 11:09
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@Log4j2
public class FeignConfiguration {

    /**
     * 请求拦截器
     */
    @Bean
    public RequestInterceptor headerInterceptor() {
        return requestTemplate -> {
            Integer type = ContextUtils.getHeadType();
            if (Constants.HeadType.SYS.checkCode(type)) {
                setSysHead(requestTemplate);
            } else if (Constants.HeadType.WX.checkCode(type)) {
                setWxHead(requestTemplate);
            } else if (Constants.HeadType.Ignore.checkCode(type)) {
                setWxHead(requestTemplate);
            } else {
                throw new RuntimeException("HeadType 类型错误");
            }
            requestTemplate.header("auth", Constants.AUTH);
        };
    }

    public void setSysHead(RequestTemplate requestTemplate) {
        String json = JSONObject.toJSONString(ContextUtils.getSysUser());
        Base64 base64 = new Base64();
        try {
            requestTemplate.header(Constants.HEAD_USER_ID, base64.encodeToString(json.getBytes("UTF-8")));
            requestTemplate.header(Constants.HEAD_TYPE, String.valueOf(ContextUtils.getHeadType()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public void setWxHead(RequestTemplate requestTemplate) {
        requestTemplate.header(Constants.HEAD_TYPE, String.valueOf(ContextUtils.getHeadType()));
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有，根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        return new okhttp3.OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool())
                .build();
    }


}
